﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Demo.Services.View.Controllers;
using Demo.Services.Contracts.DTO.Infos;
using Demo.CommonBase.Logging;
using Demo.CommonBase.View.Forms;
using Demo.CommonBase.Exceptions;
using System.Reflection;
using Ext.Net;
using System.Globalization;
using manager = Demo.Services.Services.Impl.Managers;
using Demo.Services.Contracts.DTO.Filters;
using Demo.Services.Contracts.Exceptions;

namespace Demo.Web.Operation
{
    public partial class AddResourceView : PageBase
    {

        #region Properties

        public int LineTimeId
        {
            get
            {
                int id = 0;
                if (Session["LineTimeId"] != null)
                {
                    id = (int)Session["LineTimeId"];
                }
                return id;
            }
            set
            {
                Session["LineTimeId"] = value;
            }
        }

        public int ProyectId
        {
            get
            {
                int id = 0;
                if (Session["ProyectId"] != null)
                {
                    id = (int)Session["ProyectId"];
                }
                return id;
            }            
        }

        public DateTime DateStart
        {
            get
            {
                DateTime date = DateTime.Now;
                if (Session["DateStart"] != null)
                {
                    date = (DateTime)Session["DateStart"];
                }
                return date;
            }
            set
            {
                Session["DateStart"] = value;
            }
        }

        public DateTime DateEnd
        {
            get
            {
                DateTime date = DateTime.Now;
                if (Session["DateEnd"] != null)
                {
                    date = (DateTime)Session["DateEnd"];
                }
                return date;
            }
            set
            {
                Session["DateEnd"] = value;
            }
        }



        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LineTimeId = string.IsNullOrEmpty(Request["Id"]) ? 0 : Convert.ToInt32(Request["Id"]);
                DateStart = string.IsNullOrEmpty(Request["DateStart"]) ? DateTime.Now : DateTime.Parse(Request["DateStart"]);
                DateEnd = string.IsNullOrEmpty(Request["DateEnd"]) ? DateTime.Now : DateTime.Parse(Request["DateEnd"]);
                dtDateStartEmployee.MinDate = DateStart;
                //dtDateStartEmployee.MaxDate = DateEnd;
                //dtDateEndEmployee.MinDate = DateStart;
                dtDateEndEmployee.MaxDate = DateEnd;
                DisabledContro();
                if (LineTimeId != 0)
                {
                    GetResourceLineTime();
                }
            }

        }

        private void GetResourceLineTime()
        {
            OperationController controller;
            ResourceInfo resource;
            try
            {
                Logger.Info();
                SetValue("LineTimeId", LineTimeId);
                controller = new OperationController();
                controller.ExecuteService(this, "Services.GetResourceLineTime");
                resource = (ResourceInfo)GetValue("ResourceInfo");
               
                if (resource != null)
                {
                    cboEmployee.SetValue(resource.Name);
                    cboEmployee.Disabled = true;
                    txtCostoEmpleado.Text = resource.Cost.ToString();
                    dtDateEndEmployee.SetValue(resource.DateEnd);
                    dtDateStartEmployee.SetValue(resource.DateStart);
                    txtResourceType.Text = resource.TypeLevel;
                    txtTecnologyEmployee.Text = GetTecnologys(resource.TecnologyList);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw new UnhandledException(MethodInfo.GetCurrentMethod(), ex);
            }
        }

        private string GetTecnologys(IList<TecnologyInfo> tecnologies)
        {
            string result = string.Empty;
            try
            {
                if (tecnologies != null)
                {
                    for (int i = 0; i < tecnologies.Count; i++)
                    {
                        if (i == 0)
                        {
                            result = tecnologies[i].Description;
                        }
                        else
                        {
                            result = string.Format("{0},{1}", result, tecnologies[i].Description);
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw new UnhandledException(MethodInfo.GetCurrentMethod(), ex);
            }

            return result;
        }

        protected void BtnSave_Click(object sender, DirectEventArgs e)
        {
            manager.OperationManager manager;
            LineTimeInfo lineTime;
            try
            {
                Logger.Info();
                manager = new manager.OperationManager();
                lineTime = GetLineTime();


                if ((DateStart >= DateTime.Parse(lineTime.DateStart) && DateStart <= DateTime.Parse(lineTime.DateEnd)) ||
                    (DateEnd >= DateTime.Parse(lineTime.DateStart) && DateEnd <= DateTime.Parse(lineTime.DateEnd)))
                {
                }

                if (LineTimeId.Equals(0))
                {
                    manager.SaveLineTime(lineTime);
                }
                else
                {
                    manager.UpdateLineTime(lineTime);
                }
                X.Js.AddScript("parentAutoLoadControl.hide();");
                X.Js.AddScript("parent.Ext.getCmp('btnRefresh').fireEvent('click');");
            }
            catch (DemoServiceException ex)
            { 
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw new UnhandledException(MethodInfo.GetCurrentMethod(), ex);
            }
        }

        private LineTimeInfo GetLineTime()
        {
            LineTimeInfo lineTime=null;
            int id;
            CultureInfo culture;
            try
            {
                lineTime = new LineTimeInfo();
                lineTime.Id = LineTimeId;
                int.TryParse(cboEmployee.SelectedItem.Value,out id);
                lineTime.ResourceId = id;
                lineTime.ProyectId = ProyectId;
                culture = new CultureInfo("es-MX");                                
                lineTime.DateStart = dtDateStartEmployee.SelectedValue == null ? string.Empty : DateTime.Parse(dtDateStartEmployee.SelectedValue.ToString(), culture).ToString("MM/dd/yyyy");
                lineTime.DateEnd = dtDateEndEmployee.SelectedValue == null ? string.Empty : DateTime.Parse(dtDateEndEmployee.SelectedValue.ToString(), culture).ToString("MM/dd/yyyy");

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw new UnhandledException(MethodInfo.GetCurrentMethod(), ex);
            }

            return lineTime;

        }

        protected void cboEmployee_SelectChange(object sender, DirectEventArgs e)
        {
            ResourceInfo resourceinfo;
            manager.ResourceManager resource;
            int id;
            try
            {
                Logger.Info();
                resource = new manager.ResourceManager();
                int.TryParse(cboEmployee.SelectedItem.Value, out id);
                resourceinfo = resource.GetResourceById(id);


                if (resourceinfo != null)
                {
                    txtResourceType.Text = resourceinfo.TypeLevel;
                    txtCostoEmpleado.Text = resourceinfo.Cost.ToString();
                    dtDateStartEmployee.Value = resourceinfo.DateStart;
                    dtDateEndEmployee.Value = resourceinfo.DateEnd;
                    txtTecnologyEmployee.Text = GetTecnologys(resourceinfo.TecnologyList);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw new UnhandledException(MethodInfo.GetCurrentMethod(), ex);
            }
        }

        private void DisabledContro()
        {
            txtCostoEmpleado.Disabled = true;
            txtResourceType.Disabled = true;
            txtTecnologyEmployee.Disabled = true;
        }

        protected void ValidationResource(object sender, RemoteValidationEventArgs e)
        {
            ComboBox combo;
            int id = 0;
            ResourceFilter filter;
            manager.ResourceManager resource;
            bool result;
            try
            {
                combo = (ComboBox)sender;                
                filter = new ResourceFilter();
                int.TryParse(combo.SelectedItem.Value, out id);
                filter.Id = id;
                filter.Name = combo.SelectedItem.Text;
                resource = new manager.ResourceManager();
                result = resource.ValidationResource(filter);

                e.Success = result;
                if(!result)
                {
                    e.ErrorMessage = "Seleccione un recurso valido";
                }

            }
            catch (Exception ex)
            {

                Logger.Error(ex);
                throw new UnhandledException(MethodInfo.GetCurrentMethod(), ex);
            }            

        }
    }
}